const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const app = express();

app.use(express.json());
app.use(express.static('public'));

// 处理历史记录保存
app.post('/api/history', async (req, res) => {
    try {
        const filePath = path.join(__dirname, 'chatHistory.txt');
        const existingData = await fs.readFile(filePath, 'utf8').catch(() => '[]');
        const history = JSON.parse(existingData);
        
        // 添加带时间戳的新记录
        history.unshift({
            timestamp: new Date().toLocaleString(),
            messages: req.body
        });
        
        await fs.writeFile(filePath, JSON.stringify(history));
        res.sendStatus(200);
    } catch (error) {
        res.status(500).send('保存失败: ' + error.message);
    }
});

// 处理历史记录读取
app.get('/get-history', async (req, res) => {
    try {
        const filePath = path.join(__dirname, 'chatHistory.txt');
        const data = await fs.readFile(filePath, 'utf8');
        res.json(JSON.parse(data || '[]'));
    } catch (error) {
        res.json([]);
    }
});

app.listen(3000, () => console.log('服务运行在端口3000'));